<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<span>发布商品</span>
		</div>
		<el-form ref="form" :rules="rules" label-width="120px" label-position='left' :model="form">
			<el-form-item label="商品分类" prop="cate_1st" >
				<!--  -->
				<el-select placeholder="请选择活动区域"  v-model="form.cate_1st" @change="goodsOptionsFirst(form.cate_1st)">
					<el-option v-for="(item) in goodsOptions_1st" :label="item.name" :key='item.id' :value="item.id">
					</el-option>
				</el-select>
				<el-select placeholder="请选择活动区域" v-model="form.cate_2nd" @change="goodsOptionsSecond(form.cate_2nd)">
					<el-option v-for="(item) in goodsOptions_2nd" :label="item.name" :key='item.id' :value="item.id">
					</el-option>
				</el-select>
				<el-select placeholder="请选择活动区域" v-model="form.cate_3rd">
					<el-option v-for="(item) in goodsOptions_3rd" :label="item.name" :key='item.id' :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<!--  -->
			<el-form-item label="商品名称" prop="name">
				<el-input width="80px" style="width:60vw" v-model="form.name"></el-input>
				<p class="small-title">商品标题名称长度至少3个字符，最长200个汉字</p>
			</el-form-item>
			<!--  -->
			<el-form-item label="商品卖点">
				<el-input type="textarea" style="width:60vw" v-model="form.hotPoint"></el-input>
				<p class="small-title">商品卖点不能超过140个汉字</p>
			</el-form-item>
			<!--  -->
			<el-form-item label="商品价格" prop="price">
				<el-input placeholder="" style="width:15vw" v-model="form.price">
					<template slot="append">元</template>
				</el-input>
				<p class="small-title">价格必须是0-999999之间的数字，且不能高于市场价</p>
				<p class="small-title">此价格为商品实际销售价格，如果商品存在规格，改价格显示最低价格</p>
			</el-form-item>
			<!--  -->
			<el-form-item label="市场价" prop="marketPrice">
				<el-input placeholder="" style="width:15vw" v-model="form.marketPrice">
					<template slot="append">元</template>
				</el-input>
				<p class="small-title">价格必须是0-999999之间的数字，此价格仅为市场参考价，请根据实际情况认真填写</p>
			</el-form-item>
			<!--  -->
			<el-form-item label="成本价" prop="cost">
				<el-input placeholder="" v-model="form.cost" style="width:15vw">
					<template slot="append">元</template>
				</el-input>
				<p class="small-title">价格必须是0-999999之间的数字，此价格为商户对所销售的商品的实际成本价进行备注记录，非必填选项，不会在前台销售页面中显示</p>
			</el-form-item>
			<!--  -->
			<el-form-item label="折扣" prop="discount">
				<el-input placeholder="" v-model="form.discount+''" style="width:15vw">
					<template slot="append">%</template>
				</el-input>
				<p class="small-title">根据销售价与市场价比例自动生成不需要编辑</p>
			</el-form-item>
			<!--  -->
			<el-form-item label="商品库存" prop="inventory">
				<el-input placeholder="" v-model="form.inventory" style="width:15vw"></el-input>
				<p class="small-title">库存必须是0-999999之间的整数</p>
				<p class="small-title">若启动了库存配置，则系统自动计算商品的总数，此处无需卖家填写</p>
			</el-form-item>
			<!--  -->
			<el-form-item label="商品货号" prop="articleNo">
				<el-input placeholder="" v-model="form.articleNo" style="width:15vw"></el-input>
				<p class="small-title">商品货号是商家管理商品的编号，买家不可见</p>
				<p class="small-title">最多输入20个字符，只支持输入中文、字母、数字、_、/、-和小数点</p>
			</el-form-item>
			<!--  -->
			<el-form-item label="商品主图" prop="img_lg">
				<single-upload :src.sync='form.img_lg' upload-action='/api/upload/goods' @success="_success($event)"
					remove-action='/api/upload' :headers='header'></single-upload>
				<p class="small-title">上传商品默认主图，如多规格时将默认图片或分规格上传规格主图，支持jpg、if、png格式上传或从图片空间选中，建议使用尺寸
					800*800像素以上，大小不超过1M的正方形图片，上传后的图片将自动保存在图片空间的默认分类中</p>
			</el-form-item>
			<!--  -->
			<el-form-item label="商品轮播图" prop="slider">
				<multi-upload 
				    :fileLists.sync="fileList" 
				    @fileListSuccess="_fileListSuccess($event)" 
				    upload-action="/api/upload/slider" 
				    remove-action='/api/upload'
				    :headers='header'>
				</multi-upload>
				<p class="small-title">上传商品默认主图，如多规格时将默认图片或分规格上传规格主图，支持jpg、if、png格式上传或从图片空间选中，建议使用尺寸
					800*800像素以上，大小不超过1M的正方形图片，上传后的图片将自动保存在图片空间的默认分类中</p>
			</el-form-item>
			<!--  -->
			<div class="section-title">商品详情描述</div>
			<!--  -->
			<el-form-item label="商品品牌" prop="name">
				<el-input width="80px" v-model="form.brand" style="width:60vw"></el-input>
			</el-form-item>
			<!--  -->
			<el-form-item label="商品描述" prop="detail">
				<div id="editor" v-model="form.detail">
				</div>
			</el-form-item>
			<!--  -->
			<div class="section-title">商品物流信息</div>
			<!--  -->
			<el-form-item label="所在地">
				<!--  -->
				<el-select placeholder="请选择省份" v-model="logisticsForm.province_id">
					<el-option v-for="item in provinceOptions" :label="item.name" :key='item.id'
						:value="item.province_id">
					</el-option>
				</el-select>
				<el-select placeholder="请选择市区" v-model="logisticsForm.city_id">
					<el-option v-for="item in cityOptions" :label="item.name" :key='item.id' :value="item.city_id">
					</el-option>
				</el-select>
				<el-select placeholder="请选择县" v-model="logisticsForm.county_id">
					<el-option v-for="item in countyOptions" :label="item.name" :key='item.id' :value="item.county_id">
					</el-option>
				</el-select>
				<el-select placeholder="请选择街道" v-model="logisticsForm.town_id">
					<el-option v-for="item in townOptions" :label="item.name" :key='item.id' :value="item.town_id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="商品价格" prop="freight">
				<el-input placeholder="" style="width:15vw" v-model="form.freight">
					<template slot="append">元</template>
				</el-input>
				<p class="small-title">运费设为0，前台商品将显示免运费</p>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleSave">提交</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
	import wangEditor from 'wangeditor';
	import singleUpload from '@/components/SingleUpload.vue'
	import MultiUpload from '@/components/MultiUpload.vue'
	import { Goods, Category, Address } from '@/api/';

	export default {
		components: {
			singleUpload,
			MultiUpload
		},
		data() {
			return {
				header: {
					Authorization: `Bearer ${sessionStorage.token}`
				},
				dialogImageUrl: '',
				dialogVisible: false,
				editor: '',
				form: {
					cate_1st: '',
					cate_2nd: '',
					cate_3rd: '',
					name: '',
					hotPoint: '',
					price: '',
					marketPrice: '',
					cost: '',
					discount: '',
					inventory: '',
					articleNo: '',
					img_lg: '',
					img_md: '',
					slider: '',
					brand: '',
					freight: '',
					detail:''
				},
				logisticsForm: {
					province_id: '110000000000',
					city_id: '',
					county_id: '',
					town_id: ''
				},
				rules: {
				     cate_1st: [{ type: 'number', required: true, message: '请选择一级分类', trigger: 'blur' }],
				     cate_2nd: [{ type: 'number', required: true, message: '请选择二级分类', trigger: 'change' }],
				     cate_3rd: [{ type: 'number', required: true, message: '请选择三级分类', trigger: 'change' }],
				     name: [
				      { type: 'string', required: true, message: '请填写商品名称', trigger: 'blur' },
				      { min: 3, max: 200, message: '请填写 3 至 200 个字符', trigger: 'blur' },
				     ],
				     hotPoint: [
				      { min: 0, max: 140, message: '请填写最多 140 个字符', trigger: 'blur' },
				     ],
				     price: [
				      { required: true, message: '请填写商品价格', trigger: 'blur' },
				      { type: 'number', min: 0, max: 999999, message: "商品价格0-999999之间的数", trigger: 'blur' },
				     ],
				     marketPrice: [
				      { required: true, message: '请填写市场价格', trigger: 'blur' },
				      { type: "number", min: 0, max: 999999, message: "市场价格0-999999之间的数", trigger: 'blur' },
				     ],
				     cost: [
				      { required: true, message: '请填写成本价格', trigger: 'blur' },
				      { type: 'number', min: 0, max: 999999, message: "成本价格0-999999之间的数", trigger: 'blur' },
				     ],
				     inventory: [
				      { required: true, message: '请填写库存', trigger: 'blur' },
				      { type: 'number', min: 0, max: 999999, message: "成本价格0-999999之间的数", trigger: 'blur' },
				     ],
				     articleNo: [
				      { required: true, message: '请填写货号', trigger: 'blur' },
				      { pattern: /^[\u4e00-\u9fa5,.!_\/……a-zA-Z\d]{1,20}$/, message: "请填写正确货号", trigger: 'blur' },
				     ],
				     img_lg: [
				      { required: true, message: '请上传主图', trigger: 'blur' },
				     ],
				     slider: [
				      { required: true, message: '请上传轮播图', trigger: 'blur' },
				     ],
				     brand: [
				      { required: true, message: '请填写商品品牌', trigger: 'blur' },
				     ],
				     detail: [
				      { required: true, message: '请填写商品详情', trigger: 'blur' },
				     ],
				     freight: [
				      { required: true, message: '请填写商品运费', trigger: 'blur' },
				     ]
				    },
				fileList:[],
				goodsOptions_1st: [],
				goodsOptions_2nd: [],
				goodsOptions_3rd: [],

				provinceOptions: [],
				cityOptions: [],
				countyOptions: [],
				townOptions: [],
			};
		},
		async mounted() {
			//记加商品详情
			let article = await this.loadList(this.$route.params)
			//加载一级
			this.goodsOptions_1st = await this.loadSubcate(1);
			//加载二级
			this.goodsOptions_2nd = await this.loadSubcate(article.cate_1st);
			//加载三级
			this.goodsOptions_3rd = await this.loadSubcate(article.cate_2nd);
			//加载省
			this.provinceOptions = await this.loadProvince();
			
			this.form = article;

			//初始化富文本编辑器
			const editor = new wangEditor('#editor');
			// 配置 onchange 回调函数，将数据同步到 vue 中
			editor.config.onchange = (newHtml) => {
				this.form.detail = newHtml
			};
			//配置onchange回调函数
			editor.config.uploadImgServer = '/api/upload/editor'
			//大小限制
			editor.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
			//类型限制
			editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png']
			//设置token
			editor.config.uploadImgHeaders = {
				Authorization: ` Bearer ${sessionStorage.token}`
			}
			//图片名
			editor.config.uploadFileName = 'file'

			//创建编辑器
			editor.create();
			//还原富文本编辑器内容
			editor.txt.html(this.form.detail);

			this.editor = editor;
		},
		methods: {
			_success(data) {
				this.form.img_lg = data.lgImg;
				this.form.img_md = data.mdImg;
			},
			
			_fileListSuccess(data){
				this.form.slider=data
			},
			
			async goodsOptionsFirst(id) {
				this.goodsOptions_2nd = await this.loadSubcate(id);
				if (this.goodsOptions_2nd.length) {
					this.form.cate_2nd = this.goodsOptions_2nd[0].id;
				} else {
					this.form.cate_2nd = ''
				}
				this.goodsOptionsThird()
			},
			async goodsOptionsSecond(id) {
				this.goodsOptions_3rd = await this.loadSubcate(id);
				if (this.goodsOptions_2nd.length) {
					this.form.cate_3rd = this.goodsOptions_3rd[0].id;
				} else {
					this.form.cate_3rd = ''
				}
			},
			async goodsOptionsThird() {
				this.goodsOptions_3rd = await this.loadSubcate(this.form.cate_2nd);
				if (this.goodsOptions_2nd.length) {
					this.form.cate_3rd = this.goodsOptions_3rd[0].id;
				} else {
					this.form.cate_3rd = ''
				}
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},

			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			async loadList(id) {
				let { status, data } = await Goods.info(id);
				if (status) {
					if(data.slider!=''){
						let newSlider = data.slider.split(",");
						newSlider.forEach((item, index) => { 
							let obj = { url: item };
							this.fileList.push(obj) 
						});
					}
					return data;
				}
			},
			async loadSubcate(pId) {
				let { status, data } = await Category.sub({ pId });
				if (status) {
					return data;
				}
			},

			async loadProvince() {
				let { status, data } = await Address.province();
				if (status) {
					return data;
				}
			},
			
			async handleSave(){
				this.$refs.form.validate(async (valid) => {
					if (valid) {
						let {status} = await Goods.edit({...this.form})
						if (status) {
							this.$message.success('保存成功！');
						} else {
							this.$message.error('保存失败！')
						}
					}
				})
			}
		},

	}
</script>

<style lang="less" scoped>
	.box-card {
		.el-select {
			width: 10vw;
			margin: 0 3vw;

			&:first-child {
				margin-left: 0px;
			}
		}

		.small-title {
			font-size: 12px;
			color: #999999;
			margin: 0;
		}

		.section-title {
			background-color: #f5f5f5;
			padding: 10px;
			margin-bottom: 10px;
		}
	}
</style>
<style lang="less">
	.w-e-menu {
		z-index: 2 !important;
	}

	.w-e-text-container {
		z-index: 1 !important;
		min-height: 300px !important;
		height: 100% !important;
	}
	.w-e-toolbar{
		z-index: 1 !important;
	}
</style>
